# -*- coding: utf-8 -*-
# !/usr/bin/python3
import argparse
import os
import re
from enum import Enum


class FileType(Enum):
    Dir = 0,
    File = 1,
    Title = 2,


def run():
    check_output()
    attrs = file_parser()
    create_models(attrs)


def check_output():
    global output
    dir_path = os.path.dirname(path)
    file_name = os.path.basename(path)
    if len(output) == 0:
        file_dir = file_name.split('.')[0]
        output = os.path.join(dir_path, file_dir)

    if not os.path.exists(output):
        os.makedirs(output)


def file_parser():
    attrs = []
    with open(path, 'r') as file:
        placeholder = word * indent
        for line in file.readlines():
            line = line.replace('\n', '')
            if len(line.replace(word, '')) == 0:
                continue
            level = len(re.findall(placeholder, line))
            name = line.strip(word)
            if level < file_level:
                type = FileType.Dir
            elif level == file_level:
                type = FileType.File
            else:
                type = FileType.Title
            attrs.append((name, type, level))
    return attrs


def revert_path_with_levels(path, diff_level):
    for i in range(diff_level):
        path = os.path.dirname(path)
    return path


def create_models(attrs):
    global file_index
    # global output, file_level
    current_level = 0
    current_path = output
    for (name, type, level) in attrs:
        # 创建文件夹|文件
        if type != FileType.Title:
            # 目录回退
            if level < current_level:
                current_path = revert_path_with_levels(current_path, current_level - level)
            elif level == current_level:
                current_path = revert_path_with_levels(current_path, 1)
            # 创建文件夹
            if type == FileType.Dir:
                dest_path = os.path.join(current_path, name)
                os.makedirs(dest_path)
            # 创建文件
            else:
                file_name = '[' + str(file_index).zfill(3) + ']' + name + '.md'
                dest_path = os.path.join(current_path, file_name)
                file_index = file_index + 1
                header = '# ' + name + '\n'
                with open(dest_path, 'a') as file:
                    file.write(header)
                    file.close()

            current_level = level
            current_path = dest_path

        # 创建标题
        else:
            with open(current_path, 'a') as file:
                title = '#' * (level - file_level + 1)
                title = title + ' ' + name + '\n'
                file.write(title)
                file.close()


opt_parser = argparse.ArgumentParser()
opt_parser.add_argument('path', help='目录路径')
opt_parser.add_argument('-c', help='缩进字符', dest='word', default=' ')
opt_parser.add_argument('-i', help='缩进数量', dest='indent', default=4)
opt_parser.add_argument('-f', help='文件级别（小于是目录，大于是文件内标题）', dest='file_level', default=1)
opt_parser.add_argument('-o', help='输出路径', dest='output', default='')

args = opt_parser.parse_args()
path = args.path
word = args.word
indent = args.indent
file_level = args.file_level
file_index = 0
output = args.output

run()

